﻿using Cyss.Core.Api.JWT;
using Cyss.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace Cyss.Core.Api
{
    public class TokenFilter : Attribute, IActionFilter
    {
        private ITokenHelper tokenHelper;
        public TokenFilter(ITokenHelper _tokenHelper) //通过依赖注入得到数据访问层实例
        {
            tokenHelper = _tokenHelper;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {

        }
        public void OnActionExecuting(ActionExecutingContext context)
        {
            OperateResult OperateResult = new OperateResult();
            //获取token
            var tokenobj = context.HttpContext.Request.Headers["ApiToken"];

            if (tokenobj.Count<=0)
            {
                OperateResult.CodeType=OperateResultCodeType.TokenFail;
                OperateResult.Message = "token不能为空";
                context.Result = new JsonResult(OperateResult);
                return;
            }

            string token = tokenobj[0];

            if (string.IsNullOrWhiteSpace(token))
            {
                OperateResult.CodeType=OperateResultCodeType.TokenFail;
                OperateResult.Message = "token不能为空";
                context.Result = new JsonResult(OperateResult);
                return;
            }

            string userId = "";
            //验证jwt,同时取出来jwt里边的用户ID
            TokenType tokenType = tokenHelper.ValiTokenState(token, a => a["iss"] == "WYY" && a["aud"] == "EveryTestOne", action => { userId = action["loginID"]; });
            if (tokenType == TokenType.Fail)
            {
                OperateResult.CodeType=OperateResultCodeType.TokenFail;
                OperateResult.Message = "token验证失败";
                context.Result = new JsonResult(OperateResult);
                return;
            }
            if (tokenType == TokenType.Expired)
            {
                OperateResult.CodeType=OperateResultCodeType.TokenFail;
                OperateResult.Message = "token已经过期";
                context.Result = new JsonResult(OperateResult);
            }
            if (!string.IsNullOrEmpty(userId))
            {
                //给控制器传递参数(需要什么参数其实可以做成可以配置的，在过滤器里边加字段即可)
                context.ActionArguments.Add("userId", Convert.ToInt32(userId));
            }
        }
    }
}
